/**
 * 操作日志模块 - API接口
 * @description 操作日志相关的API接口封装
 * @author CRM开发团队
 * @version 1.0.0
 */

import { request } from '@/utils/request'
import type { OperationLog, ApiResponse, PaginationResponse } from '@/api/customer'

// ==========================================
// 类型定义
// ==========================================

// 操作日志查询参数
export interface OperationLogQuery {
  page?: number
  pageSize?: number
  customerId?: number
  operationType?: 'CREATE' | 'UPDATE' | 'DELETE' | 'VIEW'
  tableName?: string
  fieldName?: string
  userId?: number
  dateStart?: string
  dateEnd?: string
  keyword?: string
  sortBy?: string
  sortOrder?: 'asc' | 'desc'
}

// 日志统计信息
export interface LogStatistics {
  totalLogs: number
  operationTypeDistribution: Record<string, number>
  tableDistribution: Record<string, number>
  userDistribution: Record<string, number>
  dailyOperations: Array<{
    date: string
    count: number
    operationTypes: Record<string, number>
  }>
}

// 日志导出请求
export interface LogExportRequest {
  query: OperationLogQuery
  format: 'excel' | 'csv'
  fields: string[]
}

// ==========================================
// API接口封装
// ==========================================

export class OperationLogAPI {
  private baseUrl = '/api/v1/operation-logs'

  /**
   * 获取操作日志列表
   */
  async getOperationLogs(params: OperationLogQuery = {}): Promise<ApiResponse<PaginationResponse<OperationLog>>> {
    return request({
      url: this.baseUrl,
      method: 'GET',
      params
    })
  }

  /**
   * 获取特定客户的操作日志
   */
  async getCustomerLogs(customerId: number, params: Omit<OperationLogQuery, 'customerId'> = {}): Promise<ApiResponse<PaginationResponse<OperationLog>>> {
    return request({
      url: `${this.baseUrl}/customer/${customerId}`,
      method: 'GET',
      params
    })
  }

  /**
   * 获取操作日志详情
   */
  async getOperationLogDetail(id: number): Promise<ApiResponse<OperationLog>> {
    return request({
      url: `${this.baseUrl}/${id}`,
      method: 'GET'
    })
  }

  /**
   * 获取操作日志统计信息
   */
  async getLogStatistics(params: {
    dateStart?: string
    dateEnd?: string
    customerId?: number
  } = {}): Promise<ApiResponse<LogStatistics>> {
    return request({
      url: `${this.baseUrl}/statistics`,
      method: 'GET',
      params
    })
  }

  /**
   * 导出操作日志
   */
  async exportLogs(data: LogExportRequest): Promise<ApiResponse<{ downloadUrl: string; taskId: string }>> {
    return request({
      url: `${this.baseUrl}/export`,
      method: 'POST',
      data
    })
  }

  /**
   * 批量删除操作日志（管理员功能）
   */
  async batchDeleteLogs(logIds: number[], deleteReason: string): Promise<ApiResponse<{ successCount: number; failedCount: number }>> {
    return request({
      url: `${this.baseUrl}/batch/delete`,
      method: 'DELETE',
      data: { logIds, deleteReason }
    })
  }

  /**
   * 清理过期日志（管理员功能）
   */
  async cleanupExpiredLogs(params: {
    beforeDate: string
    keepCriticalLogs?: boolean
  }): Promise<ApiResponse<{ deletedCount: number }>> {
    return request({
      url: `${this.baseUrl}/cleanup`,
      method: 'POST',
      data: params
    })
  }
}

// 导出API实例
export const operationLogAPI = new OperationLogAPI()

// 导出便捷方法
export default {
  // 基础查询
  getList: (params?: OperationLogQuery) => operationLogAPI.getOperationLogs(params),
  getCustomerLogs: (customerId: number, params?: Omit<OperationLogQuery, 'customerId'>) => operationLogAPI.getCustomerLogs(customerId, params),
  getDetail: (id: number) => operationLogAPI.getOperationLogDetail(id),
  
  // 统计分析
  getStatistics: (params?: { dateStart?: string; dateEnd?: string; customerId?: number }) => operationLogAPI.getLogStatistics(params),
  
  // 导出功能
  export: (data: LogExportRequest) => operationLogAPI.exportLogs(data),
  
  // 管理功能
  batchDelete: (logIds: number[], reason: string) => operationLogAPI.batchDeleteLogs(logIds, reason),
  cleanup: (params: { beforeDate: string; keepCriticalLogs?: boolean }) => operationLogAPI.cleanupExpiredLogs(params)
}